﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using HslCommunication.Core.Net;
using HslCommunication.LogNet;

namespace HslCommunication.Profinet.Sick
{
	/// <summary>
	/// Sick的扫码器的服务器信息，只要启动服务器之后，扫码器配置将条码发送到PC的指定端口上来即可，就可以持续的接收条码信息，同样也适用于海康，基恩士，DATELOGIC 。<br />
	/// The server information of Sick's code scanner, as long as the server is started, the code scanner is configured to send the barcode to the designated port of the PC, and it can continuously receive the barcode information.
	/// </summary>
	// Token: 0x02000051 RID: 81
	public class SickIcrTcpServer : NetworkServerBase
	{
		/// <summary>
		/// 实例化一个默认的服务器对象<br />
		/// Instantiate a default server object
		/// </summary>
		// Token: 0x060006BA RID: 1722 RVA: 0x00022439 File Offset: 0x00020639
		public SickIcrTcpServer()
		{
			this.initiativeClients = new List<AppSession>();
			this.lockClients = new object();
		}

		/// <summary>
		/// 当接收到条码数据的时候触发<br />
		/// Triggered when barcode data is received
		/// </summary>
		// Token: 0x1400000A RID: 10
		// (add) Token: 0x060006BB RID: 1723 RVA: 0x00022460 File Offset: 0x00020660
		// (remove) Token: 0x060006BC RID: 1724 RVA: 0x00022498 File Offset: 0x00020698
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public event SickIcrTcpServer.ReceivedBarCodeDelegate OnReceivedBarCode;

		/// <inheritdoc />
		// Token: 0x060006BD RID: 1725 RVA: 0x000224D0 File Offset: 0x000206D0
		protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint)
		{
			AppSession appSession = new AppSession();
			appSession.IpEndPoint = endPoint;
			appSession.IpAddress = endPoint.Address.ToString();
			appSession.WorkSocket = socket;
			try
			{
				socket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(this.SocketAsyncCallBack), appSession);
				this.AddClient(appSession);
			}
			catch
			{
				socket.Close();
				ILogNet logNet = base.LogNet;
				if (logNet != null)
				{
					logNet.WriteDebug(this.ToString(), string.Format(StringResources.Language.ClientOfflineInfo, endPoint));
				}
			}
		}

		// Token: 0x060006BE RID: 1726 RVA: 0x00022574 File Offset: 0x00020774
		private void SocketAsyncCallBack(IAsyncResult ar)
		{
			AppSession appSession = ar.AsyncState as AppSession;
			bool flag = appSession != null;
			if (flag)
			{
				try
				{
					appSession.WorkSocket.EndReceive(ar);
					byte[] array = new byte[1024];
					int num = appSession.WorkSocket.Receive(array);
					bool flag2 = num > 0;
					if (flag2)
					{
						byte[] array2 = new byte[num];
						Array.Copy(array, 0, array2, 0, num);
						appSession.WorkSocket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(this.SocketAsyncCallBack), appSession);
						bool flag3 = Authorization.nzugaydgwadawdibbas();
						if (flag3)
						{
							SickIcrTcpServer.ReceivedBarCodeDelegate onReceivedBarCode = this.OnReceivedBarCode;
							if (onReceivedBarCode != null)
							{
								onReceivedBarCode(appSession.IpAddress, this.TranslateCode(Encoding.ASCII.GetString(array2)));
							}
						}
					}
					else
					{
						Socket workSocket = appSession.WorkSocket;
						if (workSocket != null)
						{
							workSocket.Close();
						}
						ILogNet logNet = base.LogNet;
						if (logNet != null)
						{
							logNet.WriteDebug(this.ToString(), string.Format(StringResources.Language.ClientOfflineInfo, appSession.IpEndPoint));
						}
						this.RemoveClient(appSession);
					}
				}
				catch
				{
					Socket workSocket2 = appSession.WorkSocket;
					if (workSocket2 != null)
					{
						workSocket2.Close();
					}
					ILogNet logNet2 = base.LogNet;
					if (logNet2 != null)
					{
						logNet2.WriteDebug(this.ToString(), string.Format(StringResources.Language.ClientOfflineInfo, appSession.IpEndPoint));
					}
					this.RemoveClient(appSession);
				}
			}
		}

		// Token: 0x060006BF RID: 1727 RVA: 0x000226E4 File Offset: 0x000208E4
		private string TranslateCode(string code)
		{
			StringBuilder stringBuilder = new StringBuilder("");
			for (int i = 0; i < code.Length; i++)
			{
				bool flag = char.IsLetterOrDigit(code, i);
				if (flag)
				{
					stringBuilder.Append(code[i]);
				}
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 新增一个主动连接的请求，将不会收到是否连接成功的信息，当网络中断及奔溃之后，会自动重新连接。<br />
		/// A new active connection request will not receive a message whether the connection is successful. When the network is interrupted and crashed, it will automatically reconnect.
		/// </summary>
		/// <param name="ipAddress">对方的Ip地址</param>
		/// <param name="port">端口号</param>
		// Token: 0x060006C0 RID: 1728 RVA: 0x0002273C File Offset: 0x0002093C
		public void AddConnectBarcodeScan(string ipAddress, int port)
		{
			IPEndPoint ipendPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
			AppSession appSession = new AppSession();
			appSession.IpEndPoint = ipendPoint;
			appSession.IpAddress = ipendPoint.Address.ToString();
			ThreadPool.QueueUserWorkItem(new WaitCallback(this.ConnectBarcodeScan), appSession);
		}

		// Token: 0x060006C1 RID: 1729 RVA: 0x0002278C File Offset: 0x0002098C
		private void ConnectBarcodeScan(object obj)
		{
			AppSession appSession = obj as AppSession;
			bool flag = appSession != null;
			if (flag)
			{
				OperateResult<Socket> operateResult = base.CreateSocketAndConnect(appSession.IpEndPoint, 5000);
				bool flag2 = !operateResult.IsSuccess;
				if (flag2)
				{
					Thread.Sleep(1000);
					ThreadPool.QueueUserWorkItem(new WaitCallback(this.ConnectBarcodeScan), appSession);
				}
				else
				{
					appSession.WorkSocket = operateResult.Content;
					try
					{
						appSession.WorkSocket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(this.InitiativeSocketAsyncCallBack), appSession);
						this.AddClient(appSession);
					}
					catch
					{
						appSession.WorkSocket.Close();
						ThreadPool.QueueUserWorkItem(new WaitCallback(this.ConnectBarcodeScan), appSession);
					}
				}
			}
		}

		// Token: 0x060006C2 RID: 1730 RVA: 0x00022860 File Offset: 0x00020A60
		private void InitiativeSocketAsyncCallBack(IAsyncResult ar)
		{
			AppSession appSession = ar.AsyncState as AppSession;
			bool flag = appSession != null;
			if (flag)
			{
				try
				{
					appSession.WorkSocket.EndReceive(ar);
					byte[] array = new byte[1024];
					int num = appSession.WorkSocket.Receive(array);
					bool flag2 = num > 0;
					if (flag2)
					{
						byte[] array2 = new byte[num];
						Array.Copy(array, 0, array2, 0, num);
						appSession.WorkSocket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(this.InitiativeSocketAsyncCallBack), appSession);
						bool flag3 = Authorization.nzugaydgwadawdibbas();
						if (flag3)
						{
							SickIcrTcpServer.ReceivedBarCodeDelegate onReceivedBarCode = this.OnReceivedBarCode;
							if (onReceivedBarCode != null)
							{
								onReceivedBarCode(appSession.IpAddress, this.TranslateCode(Encoding.ASCII.GetString(array2)));
							}
						}
					}
					else
					{
						Socket workSocket = appSession.WorkSocket;
						if (workSocket != null)
						{
							workSocket.Close();
						}
						ILogNet logNet = base.LogNet;
						if (logNet != null)
						{
							logNet.WriteDebug(this.ToString(), string.Format(StringResources.Language.ClientOfflineInfo, appSession.IpEndPoint));
						}
						this.RemoveClient(appSession);
					}
				}
				catch
				{
					Socket workSocket2 = appSession.WorkSocket;
					if (workSocket2 != null)
					{
						workSocket2.Close();
					}
					ILogNet logNet2 = base.LogNet;
					if (logNet2 != null)
					{
						logNet2.WriteDebug(this.ToString(), string.Format(StringResources.Language.ClientOfflineInfo, appSession.IpEndPoint));
					}
					this.RemoveClient(appSession);
					bool isStarted = base.IsStarted;
					if (isStarted)
					{
						this.ConnectBarcodeScan(appSession);
					}
				}
			}
		}

		/// <summary>
		/// 获取当前在线的客户端数量<br />
		/// Get the number of clients currently online
		/// </summary>
		// Token: 0x1700014A RID: 330
		// (get) Token: 0x060006C3 RID: 1731 RVA: 0x000229E4 File Offset: 0x00020BE4
		public int OnlineCount
		{
			get
			{
				return this.clientCount;
			}
		}

		// Token: 0x060006C4 RID: 1732 RVA: 0x000229EC File Offset: 0x00020BEC
		private void AddClient(AppSession session)
		{
			object obj = this.lockClients;
			lock (obj)
			{
				this.clientCount++;
				this.initiativeClients.Add(session);
			}
		}

		// Token: 0x060006C5 RID: 1733 RVA: 0x00022A48 File Offset: 0x00020C48
		private void RemoveClient(AppSession session)
		{
			object obj = this.lockClients;
			lock (obj)
			{
				this.clientCount--;
				this.initiativeClients.Remove(session);
			}
		}

		/// <inheritdoc />
		// Token: 0x060006C6 RID: 1734 RVA: 0x00022AA4 File Offset: 0x00020CA4
		protected override void CloseAction()
		{
			object obj = this.lockClients;
			lock (obj)
			{
				for (int i = 0; i < this.initiativeClients.Count; i++)
				{
					Socket workSocket = this.initiativeClients[i].WorkSocket;
					if (workSocket != null)
					{
						workSocket.Close();
					}
				}
				this.initiativeClients.Clear();
			}
		}

		/// <inheritdoc />
		// Token: 0x060006C7 RID: 1735 RVA: 0x00022B28 File Offset: 0x00020D28
		public override string ToString()
		{
			return string.Format("SickIcrTcpServer[{0}]", base.Port);
		}

		// Token: 0x040001CA RID: 458
		private int clientCount = 0;

		// Token: 0x040001CB RID: 459
		private List<AppSession> initiativeClients;

		// Token: 0x040001CC RID: 460
		private object lockClients;

		/// <summary>
		/// 接收条码数据的委托信息<br />
		/// Entrusted information to receive barcode data
		/// </summary>
		/// <param name="ipAddress">Ip地址信息</param>
		/// <param name="barCode">条码信息</param>
		// Token: 0x020002B4 RID: 692
		// (Invoke) Token: 0x0600249A RID: 9370
		public delegate void ReceivedBarCodeDelegate(string ipAddress, string barCode);
	}
}
